package org.shoukaiseki.commons.utils.oracle;

import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;

/**
 * <br>
 *
 * @author 蒋カイセキ    Japan-Tokyo  18-10-23 下午7:56<br>
 * ブログ http://www.shoukaiseki.top/<br>
 * E-メール jiang28555@Gmail.com<br>
 **/
public class OracleCommentUtils {

    Connection connection;

    String sqlTable = ""+
            "select * from user_tab_comments where table_name=?" +
            "";



    String sqlColumn = "" +
            "select * from user_col_comments where Table_Name =:table_name and COLUMN_NAME=:column_name" +
            "";

    PreparedStatement psTable;

    PreparedStatement psColumn;


    public OracleCommentUtils(Connection connection) throws SQLException {
        this.connection=connection;
        init();
    }

    private void init() throws SQLException {

        psTable = connection.prepareStatement(sqlTable);
        psColumn=connection.prepareStatement(sqlColumn);
    }

    public Optional<String> getTableComment(String schemaName,String tableName) throws SQLException {

        psTable.setString(1,tableName);
//        System.out.println("sql=\n"+sqlTable);
//        System.out.println("schemaName="+schemaName);
//        System.out.println("tableName="+tableName);
        ResultSet rs = psTable.executeQuery();
        if(rs.next()){
            String table_comment = rs.getString("COMMENTS");
//            System.out.println("rs.next.table_comment="+table_comment);
            return Optional.of(table_comment);
        }
//        System.out.println("rs.nonext");
        return Optional.empty();
    }

    public Optional<String> getColumnComment(String schemaName,String tableName,String columnName) throws SQLException {

        psColumn.setString(1,tableName);
        psColumn.setString(2,columnName);
        ResultSet rs = psColumn.executeQuery();
        if(rs.next()){
//            PrintResultSet.printSingle(rs);
//            String tableComment = rs.getString("table_comment");
            String columnComment = rs.getString("COMMENTS");
            return Optional.of(columnComment);
        }
        return Optional.empty();
    }



}
